package com.tars.txtm.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * @author: Franz 2022/3/19
 */
@Component
public class NettyClient implements InitializingBean {

    private NettyClientHandler handler = null;

    public void afterPropertiesSet() throws Exception {
        System.out.println("启动netty客户端");
        start("localhost",8000);
    }

    private void start(String host, int port) {
        handler = new NettyClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("handler", handler);

            }
        });
        try {
            bootstrap.connect(host,port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void send(JSONObject msg){
        try {
            handler.call(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
